﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Wicresoft.JDPostBoard.Entity;
using Wicresoft.Common;
using Wicresoft.Common.MessagesWebService;
using Wicresoft.Framework.Organization;
using System.Text;
public partial class Gift_ApplyView : BaseAuthenticationPage
{
    public Guid ApplyID
    {
        get
        {
            if (Request["ApplyID"] != null)
                return new Guid(Request["ApplyID"]);
            return Guid.Empty;
        }
    }

    protected DataTable DTData
    {
        get
        {
            if (ViewState["DTData"] == null)
                ViewState["DTData"] = new DataTable();
            return ViewState["DTData"] as DataTable;
        }
        set
        {
            ViewState["DTData"] = value;
        }
    }


    public string SearchClause
    {
        get
        {
            if (ViewState["SearchClause"] == null)
                ViewState["SearchClause"] = "1=1";
            return ViewState["SearchClause"].ToString();
        }
        set
        {
            ViewState["SearchClause"] = value;
        }
    }

    public int Button2Label
    {
        get
        {
            if (ViewState["Button2Label"] != null)
                return int.Parse(ViewState["Button2Label"].ToString());
            return 0;
        }
        set
        {
            ViewState["Button2Label"] = value;
        }
    }

    protected int UserType
    {
        get
        {
            if (ViewState["UserType"] == null)
            {
                if (!string.IsNullOrEmpty(Request["UserType"]))
                    return int.Parse(Request["UserType"]);
                else
                    return int.MinValue;
            }
            else
            {
                return int.Parse(ViewState["UserType"].ToString());
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.UseTabber = true;
        this.Title = "申请详细信息";

        ApplyLog ol = new ApplyLog(ApplyID);
        ol.Load();

        switch (UserType)
        {
            case 1://SupplyList
                if (CurrentUser.ID.ToString() == ol.ApplierID)
                {
                    switch (ol.Status)
                    {
                        case "待审核":
                            this.tdCancel.Visible = true;
                            break;
                        case "已到货":
                            this.tdConfirm.Visible = true;
                            this.tableDeal.Visible = false;
                            this.tableConfirm.Visible = true;
                            this.tbShyj.Attributes.Add("readonly", "readonly");
                            break;
                        case "审核通过":
                            this.tableDeal.Visible = true;
                            this.tableConfirm.Visible = false;
                            this.tbShyj.Attributes.Add("readonly", "readonly");
                            //RequiredFieldValidator4.Visible=false;
                            //RequiredFieldValidator4.Enabled=false;
                            break;
                        case "延后审核已发货":
                            this.tdCancel.Visible = true;
                            break;
                        default:
                            this.tableDeal.Visible = false;
                            this.tableConfirm.Visible = true;
                            break;
                    }
                }

                break;
            case 2://LeaderView
                if (ol.Status == "待审核")
                {
                    this.tdPass.Visible = true;
                    this.fg1.Visible = true;
                    this.tdNotPass.Visible = true;
                    //SearchClause += string.Format(" AND {0} = '{1}'", ApplyLog.SQLCOL_STATUS, Enum.ApplyStatusEnum.待审核.ToString());
                }
                else if (ol.Status == "延后审核已发货")
                {
                    this.tdPass.Visible = true;
                    this.fg1.Visible = true;
                    this.tdNotPass.Visible = true;
                }
                else if (ol.Status == "延后审核")
                {
                    this.tdPass.Visible = true;
                    this.fg1.Visible = true;
                    this.tdNotPass.Visible = true;
                }





                //this.tbSupplier.Visible = false;
                //SearchClause += string.Format(" AND {0} != '{1}'", ApplyLog.SQLCOL_STATUS, Enum.ApplyStatusEnum.已取消.ToString());
                break;
            case 3://PassSupplyList
                if (ol.Status == "审核通过")
                {
                    this.tdArrival.Visible = true;
                    this.fg5.Visible = true;

                    //SearchClause += string.Format(" AND ({0} = '{1}' OR {0} = '{2}')", ApplyLog.SQLCOL_STATUS, Enum.ApplyStatusEnum.审核通过.ToString());
                }
                break;
            default:
                break;
        }

        if (!IsPostBack)
        {
            //InitControl();
            SearchClause += string.Format(" AND {0} = '{1}'", ApplyLog.SQLCOL_APPLYID, ApplyID);
            LoadFromEntity(ol);
            BindData();
        }
    }

    protected void InitControl()
    {
        DataTable dt = null;
        //if (AppConfig.Leaders.IndexOf("," + CurrentUser.Name + ",", StringComparison.CurrentCultureIgnoreCase) != -1)
        //{
        //    dt = new DataTable();
        //    dt.Columns.Add("DisplayName");
        //    dt.Columns.Add("ID");

        //    DataRow dr = dt.NewRow();
        //    dr["DisplayName"] = CurrentUser.DisplayName;
        //    dr["ID"] = CurrentUser.ID;
        //    dt.Rows.Add(dr);

        //}
        //else
        //{
        //    dt = Wicresoft.Framework.Organization.OrganizationHelper.GetUserInfoTableByDepartmentWithRole(CurrentUser.MainDepartmentID, false, new Guid(System.Configuration.ConfigurationManager.AppSettings["OfficeLeaderID"].ToLower()));


        //}

        dt = DataAccess.ExecuteSql("JDPB.ConnectionString", "select UserID as ID,UserDisplayName as DisplayName from giftcharge where  DepartmentID='" + CurrentUser.MainDepartmentID + "'").Tables[0];

        this.ddlAuditor.DataSource = dt;
        this.ddlAuditor.DataTextField = "DisplayName";
        this.ddlAuditor.DataValueField = "ID";

        this.ddlAuditor.DataBind();

        if (Wicresoft.Framework.Organization.OrganizationHelper.IsUserInRole(CurrentUser.ID, new Guid(System.Configuration.ConfigurationManager.AppSettings["OfficeAdminID"].ToLower())))
            this.ddlAuditor.Enabled = true;
        else
            this.ddlAuditor.Enabled = false;
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        BindData();
        ClientScript.RegisterStartupScript(this.GetType(), "Finish", "<script>parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

    }

    protected void LoadFromEntity(ApplyLog log)
    {
        this.ltApplicant.Text = log.ApplierDsName;
        this.ltDepart.Text = log.ApplierDepartment;
        this.ltTime.Text = log.ApplyTime.ToString();
        this.ltTitle.Text = log.ApplyTitle;
        this.ltRemark.Text = log.Remark;
        this.tbShyj.Value = log.DealContent;
        this.ltTotal.Text = log.ApplyCost.ToString("N");

        this.ltApplicant2.Text = log.ApplierDsName;
        this.ltDepart2.Text = log.ApplierDepartment;
        this.ltTime2.Text = log.ApplyTime.ToString();
        this.ltTitle2.Text = log.ApplyTitle;
        this.ltRemark2.Text = log.Remark;
        this.tbShyj2.Text = log.DealContent;
        this.ltTotal2.Text = log.ApplyCost.ToString("N");
        if (log.AuditorID != "")
        {
            ListItem itemAll = new ListItem();
            itemAll.Text = log.AuditorDisplay;
            itemAll.Value = log.AuditorID;
            this.ddlAuditor.Items.Insert(0, itemAll);

        }
        if (log.NiLingquTime != DateTime.MinValue)
        {
            ltNilingqu.Text = log.NiLingquTime.ToString();
        }
        if (log.DealTime != DateTime.MinValue)
            this.ltShsj.Text = log.DealTime.ToString();


        ListItem li = ddlAuditor.Items.FindByValue(log.AuditorID);
        if (li != null)
        {
            this.ddlAuditor.SelectedValue = li.Value;
        }
        if (log.ArrivalTime == DateTime.MinValue)
        {
            this.ltArrivalTime.Text = string.Empty;
        }
        else
        {
            this.ltArrivalTime.Text = log.ArrivalTime.ToString();
        }
    }

    private void BindData()
    {
        DTData = DataAccess.Select(typeof(Apply_Gift_Relation), SearchClause, Apply_Gift_Relation.SQLCOL_ID);
        rptProduct.DataSource = DTData;
        rptProduct.DataBind();


    }

    protected void PassSupply(object sender, EventArgs e)
    {
        ApplyLog ol = new ApplyLog(ApplyID);
        ol.Load();
        if (ol.Status == Enum.ApplyStatusEnum.待审核.ToString())
        {
            ol.Status = Enum.ApplyStatusEnum.审核通过.ToString();
            ol.DealTime = DateTime.Now;

            ol.DealerID = this.ddlAuditor.SelectedValue;
            //ol.DealerName = CurrentUser.Name;
            ol.DealerDsName = this.ddlAuditor.SelectedItem.Text;

            ol.RealDealerID = CurrentUser.ID.ToString();
            ol.RealDealerName = CurrentUser.Name;
            ol.RealDealerDisplay = CurrentUser.DisplayName;

            ol.DealContent = this.tbShyj.Value;
            ol.Save();

        }
        if (ol.Status == Enum.ApplyStatusEnum.延后审核.ToString())
        {
            ol.Status = Enum.ApplyStatusEnum.审核通过.ToString();
            ol.DealTime = DateTime.Now;

            ol.DealerID = this.ddlAuditor.SelectedValue;
            //ol.DealerName = CurrentUser.Name;
            ol.DealerDsName = this.ddlAuditor.SelectedItem.Text;

            ol.RealDealerID = CurrentUser.ID.ToString();
            ol.RealDealerName = CurrentUser.Name;
            ol.RealDealerDisplay = CurrentUser.DisplayName;

            ol.DealContent = this.tbShyj.Value;
            ol.Save();

        }
        if (ol.Status == Enum.ApplyStatusEnum.延后审核已发货.ToString())
        {
            ol.Status = Enum.ApplyStatusEnum.已领取.ToString();
            ol.DealTime = DateTime.Now;

            ol.DealerID = this.ddlAuditor.SelectedValue;
            //ol.DealerName = CurrentUser.Name;
            ol.DealerDsName = this.ddlAuditor.SelectedItem.Text;

            ol.RealDealerID = CurrentUser.ID.ToString();
            ol.RealDealerName = CurrentUser.Name;
            ol.RealDealerDisplay = CurrentUser.DisplayName;

            ol.DealContent = this.tbShyj.Value;
            ol.Save();

        }


        BindData();

        #region 发送通过提醒

        User user = OrganizationHelper.GetUserInfo(ol.ApplierName);
        string mobile = string.Empty;
        if (user != null)
        {
            DataTable dtData = Wicresoft.Common.DataAccess.ExecuteSql("Wicresoft.Framework.ConnectionString",
             string.Format(@"Select ValueString from PropertyData where NodeID='{0}' and PropertyID in (
                    select ID from Property where Name='Mobile')", user.ID.ToString())).Tables[0];
            mobile = dtData.Rows.Count == 0 ? "" : dtData.Rows[0]["ValueString"].ToString();
        }
        if (mobile != string.Empty)
        {
            try
            {
                MsgUtil msgUtil = new MsgUtil(user.ID.ToString(), user.Name, user.DisplayName, mobile);
                StringBuilder sbTag = new StringBuilder();
                sbTag.Append(ol.ApplyTitle);
                msgUtil.SendMessage(CurrentUser.Name, string.Empty, "公务接待申请审核通过：" + ol.ApplyTitle, sbTag.ToString());
            }
            catch
            { }
        }
        #endregion
        ClientScript.RegisterStartupScript(this.GetType(), "RefreshParent", "<script>parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

    }
    protected void NotPassSupply(object sender, EventArgs e)
    {
        ApplyLog ol = new ApplyLog(ApplyID);
        ol.Load();
        if (ol.Status == Enum.ApplyStatusEnum.待审核.ToString())
        {
            ol.Status = Enum.ApplyStatusEnum.审核未通过.ToString();
            ol.DealTime = DateTime.Now;

            ol.DealerID = this.ddlAuditor.SelectedValue;
            //ol.DealerName = CurrentUser.Name;
            ol.DealerDsName = this.ddlAuditor.SelectedItem.Text;

            ol.RealDealerID = CurrentUser.ID.ToString();
            ol.RealDealerName = CurrentUser.Name;
            ol.RealDealerDisplay = CurrentUser.DisplayName;

            ol.DealContent = this.tbShyj.Value;
            ol.Save();
        }
        if (ol.Status == Enum.ApplyStatusEnum.延后审核.ToString())
        {
            ol.Status = Enum.ApplyStatusEnum.审核未通过.ToString();
            ol.DealTime = DateTime.Now;

            ol.DealerID = this.ddlAuditor.SelectedValue;
            //ol.DealerName = CurrentUser.Name;
            ol.DealerDsName = this.ddlAuditor.SelectedItem.Text;

            ol.RealDealerID = CurrentUser.ID.ToString();
            ol.RealDealerName = CurrentUser.Name;
            ol.RealDealerDisplay = CurrentUser.DisplayName;

            ol.DealContent = this.tbShyj.Value;
            ol.Save();
        }
        if (ol.Status == Enum.ApplyStatusEnum.延后审核已发货.ToString())
        {
            ol.Status = Enum.ApplyStatusEnum.审核未通过.ToString();
            ol.DealTime = DateTime.Now;

            ol.DealerID = this.ddlAuditor.SelectedValue;
            //ol.DealerName = CurrentUser.Name;
            ol.DealerDsName = this.ddlAuditor.SelectedItem.Text;

            ol.RealDealerID = CurrentUser.ID.ToString();
            ol.RealDealerName = CurrentUser.Name;
            ol.RealDealerDisplay = CurrentUser.DisplayName;

            ol.DealContent = this.tbShyj.Value;
            ol.Save();
        }
        BindData();

        #region 发送不通过提醒

        User user = OrganizationHelper.GetUserInfo(ol.ApplierName);
        string mobile = string.Empty;
        if (user != null)
        {
            DataTable dtData = Wicresoft.Common.DataAccess.ExecuteSql("Wicresoft.Framework.ConnectionString",
             string.Format(@"Select ValueString from PropertyData where NodeID='{0}' and PropertyID in (
                    select ID from Property where Name='Mobile')", user.ID.ToString())).Tables[0];
            mobile = dtData.Rows.Count == 0 ? "" : dtData.Rows[0]["ValueString"].ToString();
        }
        if (mobile != string.Empty)
        {
            try
            {
                MsgUtil msgUtil = new MsgUtil(user.ID.ToString(), user.Name, user.DisplayName, mobile);
                StringBuilder sbTag = new StringBuilder();
                sbTag.Append(ol.ApplyTitle);
                msgUtil.SendMessage(CurrentUser.Name, string.Empty, "公务接待申请被驳回：" + ol.ApplyTitle, sbTag.ToString());
            }
            catch
            { }
        }
        #endregion
        ClientScript.RegisterStartupScript(this.GetType(), "RefreshParent", "<script>parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

    }

    protected void ComfirmSupply(object sender, EventArgs e)
    {
        ApplyLog ol = new ApplyLog(ApplyID);
        ol.Load();
        if (ol.Status == Enum.ApplyStatusEnum.已到货.ToString())
        {
            ol.Status = Enum.ApplyStatusEnum.已领取.ToString();
            ol.ConfirmTime = Convert.ToDateTime(DateTime.Now.ToString());
            ol.Save();
        }
        BindData();
        ClientScript.RegisterStartupScript(this.GetType(), "RefreshParent", "<script>parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

    }

    protected void CancelSupply(object sender, EventArgs e)
    {
        ApplyLog ol = new ApplyLog(ApplyID);
        ol.Load();
        if (ol.Status == Enum.ApplyStatusEnum.待审核.ToString())
        {
            ol.Status = Enum.ApplyStatusEnum.已取消.ToString();
            ol.Save();

        }
        BindData();
        ClientScript.RegisterStartupScript(this.GetType(), "RefreshParent", "<script>parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");

    }
    /// <summary>
    /// 审核通过后直接由管理员领取确认
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Arrival_Click(object sender, EventArgs e)
    {
        ApplyLog ol = new ApplyLog(ApplyID);
        ol.Load();
        if (ol.Status == Enum.ApplyStatusEnum.审核通过.ToString())
        {
            ol.Status = Enum.ApplyStatusEnum.已领取.ToString();
            ol.ArrivalTime = DateTime.Now;
            ol.ArrivalOperatorID = CurrentUser.ID.ToString();
            ol.ArrivalOperatorName = CurrentUser.Name;
            ol.ArrivalOperatorDsName = CurrentUser.DisplayName;
            ol.Save();
            //if (ol.Save())
            //{
            //    string MessageTitle = "到货通知";
            //    string MessageText = "您的申请“" + ol.ApplyTitle + "”的已经到货，请及时领取！";
            //    string MessageModuleID = WebCommon.GetConfig("MessageModuleID");
            //    MessagesService ms = new MessagesService();
            //    string s = ms.SendMessageByModuleID(MessageModuleID, CurrentUser.Name, ol.ApplierName, MessageTitle, MessageText, false, 0, "", DateTime.Now.ToString());
            //    //WebCommon.ShowMessage(this, "通知成功");
            //}

        }
        BindData();
        ClientScript.RegisterStartupScript(this.GetType(), "RefreshParent", "<script>parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");
    }

    protected void Notice_Click(object sender, EventArgs e)
    {
        //ApplyLog ol = new ApplyLog(ApplyID);
        //ol.Load();
        //MessagesService ms = new MessagesService();
        //string s = ms.SendMessageByModuleID(MessageModuleID, CurrentUser.Name, ol.ApplierName, MessageTitle, MessageText, false, 0, "", DateTime.Now.ToString());
        ////Response.Write(s);
        ////Response.End();
        //BindData();
        //Response.Write("<script>alert('通知成功！');</script>");
    }

    protected void rptProduct_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        ApplyLog ol = new ApplyLog(ApplyID);
        ol.Load();
        switch (UserType)
        {
            case 1:
                if (ol.Status == Enum.ApplyStatusEnum.待审核.ToString()) { }
                // e.Item.FindControl("btnDelete").Visible = true;
                break;
            case 2:

                break;
            case 3:

                break;
            default:
                break;
        }
    }

    protected void rptProduct_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "Delete":
                Apply_Gift_Relation temp = new Apply_Gift_Relation(int.Parse(e.CommandArgument.ToString()));
                temp.Load();

                ApplyLog olist = new ApplyLog(temp.ApplyID);
                olist.Load();
                olist.ApplyCost -= temp.GiftTotal;

                olist.Save();

                temp.Delete();

                BindData();
                ClientScript.RegisterStartupScript(this.GetType(), "RefreshParent", "<script>parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");
                break;

        }
    }
}
